package com.lsh.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.lsh.order.dao.OrderDao;
import com.lsh.order.entity.Order;
import com.lsh.order.feign.AccountApi;
import com.lsh.order.feign.StorageApi;
import com.lsh.order.repository.OrderRepository;
import com.lsh.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/6/29 2:27 下午
 * @desc ：
 */
@Slf4j
@Service("OrderService")
//@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderRepository orderRepository;
    @Autowired
    AccountApi accountApi;
    @Autowired
    StorageApi storageApi;

    @Autowired
    RestTemplate restTemplate;


    @Autowired
    private OrderDao orderDao;



    @Override
    //开启 Seata 全局事务注解
//    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("------->交易开始 入参："+order);
        //本地方法
        Order save = orderRepository.save(order);
        System.out.println("入库后的save："+save);

        //远程方法 扣减库存
        log.info("Order调用Storage平台 入参：productID"+order.getProductId()+"，count："+order.getCount());
        String s1 = storageApi.decreaseStorage(order.getProductId(), order.getCount());
        log.info("Order调用Storage平台 返回："+s1);

        //远程方法 扣减账户余额
        log.info("------->扣减账户开始");
        System.out.println("调用Account服务参数："+order);
        log.info("Order调用Account平台 入参：UserID："+order.getUserId()+"，Money："+order.getMoney());

        accountApi.decreaseAccount(order.getUserId(),order.getMoney());

        log.info("------->扣减账户结束");

        log.info("------->交易结束");

    }

    @Override
    @SentinelResource("UPDATE-ORDER")
    public void update(Integer userId, Integer money, Integer status) {
        log.info("修改订单状态，入参为：userId={},money={},status={}",userId,money,status);

        orderDao.update(userId,money,status);
        log.info("修改订单状态完成");

    }

    @Override
    public String decreaseAccount() {
        String s1 = storageApi.decreaseStorage(1, 1);
        System.out.println("调用库存返回："+s1);

        String s = accountApi.decreaseAccount(1, 1);
        System.out.println("调用账号返回："+s);

        return  "success！";
    }





    /**
     * 查询所有订单
     * @return
     */
    @Override
    public List<Order> findAll() {
        return orderRepository.findAll() ;
    }
}
